#include <gtest/gtest.h>
#include "Poller/PipeWrap.h"
#include "Util/Util.h"
#include "Util/uv_errno.h"
#include "Network/sockutil.h"

namespace toolkit {

class PipeWrapTest : public ::testing::Test {
protected:
    PipeWrap pipe;
};

// 测试 PipeWrap 构造函数
TEST_F(PipeWrapTest, Constructor) {
    EXPECT_NE(pipe.getReadFd(), -1);
    EXPECT_NE(pipe.getWriteFd(), -1);
}

// 测试重新打开管道
TEST_F(PipeWrapTest, ReOpen) {
    int oldReadFd = pipe.getReadFd();
    int oldWriteFd = pipe.getWriteFd();

    pipe.reOpen();

    EXPECT_NE(pipe.getReadFd(), oldReadFd);
    EXPECT_NE(pipe.getWriteFd(), oldWriteFd);
    EXPECT_NE(pipe.getReadFd(), -1);
    EXPECT_NE(pipe.getWriteFd(), -1);
}

// 测试写入和读取数据
TEST_F(PipeWrapTest, WriteAndReadData) {
    const char testData[] = "Hello, Pipe!";
    int writeSize = sizeof(testData);

    // 写入数据
    int written = pipe.writeData(testData, writeSize);
    EXPECT_EQ(written, writeSize);

    // 读取数据
    char buffer[1024];
    int readSize = pipe.readData(buffer, sizeof(buffer));
    EXPECT_EQ(readSize, writeSize);
    EXPECT_EQ(memcmp(testData, buffer, writeSize), 0);
}

// 测试析构函数
TEST_F(PipeWrapTest, Destructor) {
    PipeWrap* tempPipe = new PipeWrap();
    int readFd = tempPipe->getReadFd();
    int writeFd = tempPipe->getWriteFd();
    delete tempPipe;

    // 由于无法直接检查文件描述符是否关闭，这里可以尝试使用 read 或 write 来验证
    char buf;
    int ret = ::read(readFd, &buf, 1);
    EXPECT_EQ(ret, -1);
    ret = ::write(writeFd, &buf, 1);
    EXPECT_EQ(ret, -1);
}

} // namespace toolkit

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}